import cv2
import numpy as np
from Python import public as pb
import matplotlib.pyplot as plt

COLOR_LOW = np.array([123, 75, 160])
COLOR_HIGH = np.array([179, 255, 255])

LOW = 340
HIGH = 400

state = 0


def make_predict_image():
    img = cv2.imread('../front/l2.jpg')
    img_HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    img_binary = cv2.inRange(img_HSV, COLOR_LOW, COLOR_HIGH)
    # cv2.imshow('f', img_binary)

    x = np.array([i for i in range(480)])
    y1 = np.array([0 for i in range(480)])
    y2 = np.array([0 for i in range(480)])

    for i in range(LOW, 479):
        for j in range(640):
            if img_binary[i][j] == 255 or img_binary[i - 1][j] == 255 or img_binary[i + 1][j] == 255:
                y1[i] = j
                break
        for j in range(640):
            if img_binary[i][639 - j] == 255 or img_binary[i - 1][639 - j] == 255 or img_binary[i + 1][
                639 - j] == 255 or img_binary[i - 2][639 - j] == 255:
                y2[i] = 639 - j
                break

    x_ = x[LOW:479]
    y1_ = y1[LOW:479]
    y2_ = y2[LOW:479]

    list1 = np.polyfit(x_, y1_, 2)
    list2 = np.polyfit(x_, y2_, 2)
    f1 = np.poly1d(list1)
    f2 = np.poly1d(list2)

    plt.plot(x_, y1_, 'r*')
    plt.plot(x_, f1(x_), '-')
    plt.plot(x_, y2_, 'r*')
    plt.plot(x_, f2(x_), '-')
    plt.xlim(0, 480)
    plt.ylim(0, 640)
    plt.show()

    img_out = np.zeros((480, 640, 3), dtype=np.uint8)
    for i in x_:
        for j in range(int(f1(i)), int(f2(i))):
            img_out[i][j][0] = 30
            img_out[i][j][1] = 200
            img_out[i][j][2] = 30

    cv2.imshow('r', img_out)
    cv2.imwrite('l2.jpg', img_out)

    pb.delay_key(0)


def gabor_filter(image, ksize, sigma, theta, lambd, gamma):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 创建Gabor滤波器
    kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, lambd, gamma, 0, cv2.CV_32F)

    # 进行滤波操作
    filtered_image = cv2.filter2D(gray, cv2.CV_8UC3, kernel)

    return filtered_image


def get_line(img):
    filtered_image = gabor_filter(img, 18, 4.1, 258 / 360 * 3.14, 13.2, 11)
    # filtered_image = gabor_filter(image, ksize, sigma, theta, lambd, gamma)
    ret, thresh = cv2.threshold(filtered_image, 230, 255, cv2.THRESH_TOZERO)
    cv2.imshow('thresh', thresh)
    return thresh


def show_pre(img, T):
    N = [0, 0, 0, 0, 0]
    for j in range(5):
        dst = cv2.addWeighted(img, 0.8, T[j], 0.2, 0)
        img_line = get_line(img)

        # 计算重合点数
        for x in range(LOW, 480):
            for y in range(640):
                if T[j][x][y][1] == 200 and img_line[x][y] == 255:
                    N[j] += 1

        cv2.imshow('t', dst)
        pb.delay_key(1)

    print(N)
    min_N = N.index(min(N))
    return min_N
